#include <rtthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static void uartrw(int argc, char **argv)
{
    int fd;
    int cnt = 100000;
    char *buf;
    int ret;
    unsigned max = 1;

    if (argc < 2)
    {
        printf("param err\n");
        return;
    }
    if (argc == 3)
        cnt = atoi(argv[2]);

    if ((buf = rt_malloc(64)) == RT_NULL)
    {
        printf("no mem\n");
        return;
    }

    if (argc == 4)
        max = atoi(argv[3]);
    if (max > 64)
        max = 64;

    printf("open %s\n", argv[1]);

    fd = open(argv[1], O_RDWR);
    if (fd < 0)
    {
        printf("open fail\n");
        goto _out;
    }

    while (cnt--)
    {
        ret = read(fd, buf, max);
        if (ret <= 0)
        {
            printf("read fail\n");
            break;
        }
        ret = write(fd, buf, ret);
        if (ret <= 0)
        {
            printf("write fail\n");
            break;
        }
    }
    close(fd);

_out:
    rt_free(buf);
    printf("uart test exit\n");
}
MSH_CMD_EXPORT(uartrw, uartrw devname [times] -- uart Read and Write);

static void uartw(int argc, char **argv)
{
    int fd;
    int cnt = 100000;
    char buf[64];
    int ret;
    unsigned max = 1;

    if (argc < 2)
    {
        printf("param err\n");
        return;
    }
    if (argc == 3)
        cnt = atoi(argv[2]);

    if (argc == 4)
        max = atoi(argv[3]);
    if (max > 64)
        max = 64;

    memset(buf, 'A', sizeof(buf));
    printf("open %s\r\n", argv[1]);

    fd = open(argv[1], O_RDWR);
    if (fd < 0)
    {
        printf("open fail\r\n");
        goto _out;
    }

    while (cnt--)
    {
        ret = write(fd, buf, max);
        if (ret <= 0)
        {
            printf("write fail\r\n");
            break;
        }
    }
    close(fd);

_out:
    printf("uart test exit\n");
}
MSH_CMD_EXPORT(uartw, uartw DEVNAME [TIMES] -- uart Write);
